<template>
  <PageDialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <PageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">产品名称：{{ info.commonName }}</div>
              <div class="lable">生产批号：{{ info.batchNumber }}</div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-input
                  v-model="filterInfo.sacnCode"
                  :clearable="true"
                  placeholder="请扫码二维码/个体码"
                  @keyup.enter.native="sacn"
                  @input="(e) => (filterInfo.sacnCode = validSe(e))"
                >
                  <el-select v-model="selectedScanValue" #prepend>
                    <el-option
                      v-for="item in selectedScanOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-input>
              </div>
            </div>
          </div>
          <div>
            <el-button style="margin-right: 10px" @click="changeNumberAll(true)"
              >一键填充数量</el-button
            >
            <el-button @click="changeNumberAll(false)">一键清空</el-button>
          </div>
        </template>
      </PageFilter>
    </div>
    <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
      <DialogTable
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        ref="depotTable"
        v-model:data="tableInfo.data"
        :api="api"
        :pager="false"
        :tabIndex="true"
        :checkBox="false"
        :listen-height="false"
        v-model:query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
      >
        <template v-slot:col-qty="scope">
          <el-input-number
            v-model="scope.row.qty"
            style="width: 100px"
            controls-position="right"
            :precision="0"
            v-enterNumber
            :disabled="scope.row.totalStockQty === 0"
            :max="scope.row.totalStockQty"
            :min="0"
          ></el-input-number>
        </template>
      </DialogTable>
    </el-form>
  </PageDialog>
</template>

<script setup name="IndividualDetails">
import { useExportDetailExtGetUnityData } from '@/api/use'

const { proxy } = getCurrentInstance()

const selectedScanOptions = ref([
  {
    label: '增加',
    value: '1',
  },
  {
    label: '减少',
    value: '2',
  },
])
const props = defineProps({
  api: {
    type: Function,
    default: useExportDetailExtGetUnityData,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
const selectedScanValue = ref('1')
const scanInput = ref('')
// 过滤相关配置
const filterInfo = ref({
  query: {
    sort: 'create_time desc',
    ...props.query,
  },
  sacnCode: '',
  list: [
    { type: 'slot', value: 'button' },
    // {type: 'input', label: '个体码', value: 'keyword', event: search},
    // {type: 'button', label: '搜索', event: search}
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '个体码', value: 'unityCode' },
    { label: '原厂码', value: 'factorySubCode' },
    {
      label: '领出仓库存量',
      value: 'totalStockQty',
      type: 'column',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '出库数量',
      value: 'qty',
      // type: "number",
      type: 'slot',
      // rules: { validator: proxy.$validate.positiveAndZero, target: "blur" }
    },
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '选择个体',
  width: '90%',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const selectRow = ref('')
const isReturnShow = ref(true)
const shows = computed({
  get() {
    return props.showDialog
  },
  set(val) {
    proxy.$emit('update:showDialog', val) // 更新父组件shows
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length > 0) {
      if (isReturnShow.value) {
        returnShow()
        isReturnShow.value = false
      }
    }
  }
)

function getList() {
  tableInfo.value.refresh = Math.random()
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  proxy.$emit('reset')
}
function sumArr(arr) {
  let sum = 0
  arr.map((i) => {
    sum += Number(i.qty)
  })
  return sum
}
function handleSave() {
  let list = tableInfo.value.data.filter((item) => item.qty > 0)
  if (!list.length) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '出库数量不能全为空或0',
    })
    return
  }
  const qtyTotal = sumArr(list)
  const param = {
    ...props.info,
    exportQty: qtyTotal,
    details: [...list],
  }
  proxy.$emit('callback', param)
  handleClose()
}
function sacn() {
  const code = filterInfo.value.sacnCode
  if (!code) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请扫码二维码/个体码',
    })
    return
  }
  const codeIndex = tableInfo.value.data.findIndex(
    (value) =>
      value.code === code ||
      value.unityCode === code ||
      value.factorySubCode === code
  )
  if (codeIndex !== -1) {
    let qty = tableInfo.value.data[codeIndex].qty
      ? tableInfo.value.data[codeIndex].qty
      : 0
    if (selectedScanValue.value === '1') {
      if (props.info.codeType !== 'unique') {
        tableInfo.value.data[codeIndex]['qty'] = qty + 1
      } else {
        tableInfo.value.data[codeIndex]['qty'] = 1
      }
    } else if (selectedScanValue.value === '2') {
      if (props.info.codeType !== 'unique') {
        tableInfo.value.data[codeIndex]['qty'] =
          qty > 0 ? (qty -= 1) : (qty = 0)
      } else {
        tableInfo.value.data[codeIndex]['qty'] = 0
      }
    }
    filterInfo.value.sacnCode = ''
    return
  } else {
    proxy.$message({
      message: '该领用出库单中没有你要领用出库的产品',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    filterInfo.value.sacnCode = ''
    return
  }
  // api().then((resp)=>{
  //   if(resp && resp.success){
  //     let data = resp.data
  //     date.qty = 1
  //     tableInfo.data.push(data)
  //   }
  //   filterInfo.value.sacnCode = ''
  // })
}
function returnShow() {
  console.log(props.info.detailExtVOS)
  if (props.info.detailExtVOS && props.info.detailExtVOS.length > 0) {
    tableInfo.value.data.forEach((row) => {
      row['qty'] = 0
      props.info.detailExtVOS.forEach((item) => {
        if (item.depotExtId === row.depotExtId) {
          row['qty'] = item.qty
        }
      })
    })
  }
}
function changeNumberAll(isAll) {
  if (isAll) {
    tableInfo.value.data.forEach((row) => {
      row.qty = row.totalStockQty || 0
    })
  } else {
    tableInfo.value.data.forEach((row) => {
      row.qty = 0
    })
  }
}
onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    // getList();
  })
})
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
